package main

import (
	"bufio"
	"fmt"
	"net"
	"log"
	"sync"
	"time"
	"os"
	"strings"
)

var (
	sIP   = "zichuandr.xyz"
	sPort = "80"
	wg sync.WaitGroup
)

func main() {
	conn, err := net.Dial("tcp", sIP+":"+sPort)
	myerr(err)
	wg.Add(1)
	go writeToServer(conn)
	go showResponse(conn)
	timeOut()
	wg.Wait()
}

func writeToServer(c net.Conn) {
	s := bufio.NewScanner(os.Stdin)
	for s.Scan() {
		b := make([]byte, 20)
		r := strings.NewReader(s.Text())
		r.Read(b)
		fmt.Println("input content:", string(b))
		_, err := c.Write(b)
		if err != nil {
			fmt.Println("writeToServer err")
		}
	}
}

func showResponse(c net.Conn) {
	s := bufio.NewScanner(c)
	for s.Scan()  {
		fmt.Fprintln(os.Stdout, "response: " + s.Text())
	}
}

func timeOut() {
	select {
	case <-time.Tick(30*time.Second):
		fmt.Println("main-timeout")
		wg.Done()
	}
}

func myerr(err error) {
	if err != nil {
		log.Fatal(err)
	}
}
